/*
 * The MIT License
 * 
 * Copyright (c) 2008 Comcast Interactive Media
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package cim.sf.core.command.sh;

import java.io.File;
import java.security.SecureRandom;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;

import cim.sf.core.command.CommandAvailabilityListener;
import cim.sf.core.command.CommandShell;

/**
 * 
 * @author <a href="mailto:jeremy_volkman@cable.comcast.com">Jeremy Volkman</a>
 *
 */
public class Activator implements BundleActivator, CommandAvailabilityListener {

    private CommandWriter commandWriter;
    private CommandServer commandServer;
    
    private ServiceTracker shellTracker;
    private ServiceRegistration listenerRegistration;
    
    int port = 29233;
    File baseDirectory;
    String key;
    boolean groupAllowed = true;
    boolean othersAllowed = false;
    
	public synchronized void start(BundleContext context) throws Exception {
	    String baseDir = System.getProperty("cim.sf.core.command.sh.basedir");
	    if (baseDir != null) {
	        this.baseDirectory = new File(baseDir);
	    } else {
	        this.baseDirectory = new File(System.getProperty("user.dir"), "cmd");
	    }
	    
        try {
            port = Integer.parseInt(System.getProperty("cim.sf.core.command.sh.port"));
        } catch (Exception e) {
        }
        
        String s = System.getProperty("cim.sf.core.command.sh.groupallowed");
        if (s != null) {
            groupAllowed = Boolean.parseBoolean(s);
        }

        s = System.getProperty("cim.sf.core.command.sh.othersallowed");
        if (s != null) {
            othersAllowed = Boolean.parseBoolean(s);
        }

        byte[] keyBytes = new byte[64];
        new SecureRandom().nextBytes(keyBytes);
        key = new String(Base64Coder.encode(keyBytes));
        
        this.shellTracker = new ServiceTracker(context, CommandShell.class.getName(), null);
        this.shellTracker.open();
	    this.commandWriter = new CommandWriter(this);
        this.commandServer = new CommandServer(this);
        this.commandServer.open();
        
        listenerRegistration = context.registerService(CommandAvailabilityListener.class.getName(), this, null);

        // Add pre-registered commands.
        // Any incoming listener 
        CommandShell shell = getCommandShell();
        if (shell != null) {
            for (String command : shell.getCommands()) {
                commandAdded(command);
            }
        }
	}

	public synchronized void stop(BundleContext context) throws Exception {
	    this.commandServer.close();
	    this.commandServer = null;
	    
	    // Remove all registered commands.
        CommandShell shell = getCommandShell();
        if (shell != null) {
            for (String command : shell.getCommands()) {
                commandRemoved(command);
            }
        }

        listenerRegistration.unregister();
	    
	    this.shellTracker.close();
	    this.shellTracker = null;
	    this.commandWriter.cleanUp();
	    this.commandWriter = null;
	    this.key = null;
	}

    public synchronized void commandAdded(String path) {
        commandWriter.writeCommand(path);
    }

    public synchronized void commandRemoved(String path) {
        commandWriter.removeCommand(path);
    }
    
    CommandShell getCommandShell() {
        if (shellTracker != null) {
            return (CommandShell) shellTracker.getService();
        }
        return null;
    }
}
